package com.roncoo.education.course.service.admin.biz;

import java.util.ArrayList;
import java.util.List;

import javax.validation.constraints.NotNull;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.roncoo.education.common.core.base.Page;
import com.roncoo.education.common.core.base.PageUtil;
import com.roncoo.education.common.core.base.Result;
import com.roncoo.education.common.core.enums.StatusIdEnum;
import com.roncoo.education.common.core.tools.BeanUtil;
import com.roncoo.education.common.core.tools.DateUtil;
import com.roncoo.education.common.elasticsearch.EsSphere;
import com.roncoo.education.common.service.BaseBiz;
import com.roncoo.education.course.dao.CategoryDao;
import com.roncoo.education.course.dao.SphereDao;
import com.roncoo.education.course.dao.impl.mapper.entity.Sphere;
import com.roncoo.education.course.dao.impl.mapper.entity.SphereExample;
import com.roncoo.education.course.dao.impl.mapper.entity.SphereExample.Criteria;
import com.roncoo.education.course.service.admin.req.AdminSphereEditReq;
import com.roncoo.education.course.service.admin.req.AdminSpherePageReq;
import com.roncoo.education.course.service.admin.req.AdminSphereSaveReq;
import com.roncoo.education.course.service.admin.resp.AdminSpherePageResp;
import com.roncoo.education.course.service.admin.resp.AdminSphereViewResp;
import com.roncoo.education.system.feign.interfaces.IFeignRoleUser;
import com.roncoo.education.user.feign.interfaces.IFeignLecturer;

import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;

/**
 * ADMIN-全景信息
 *
 * @author wujing
 */
@Component
@RequiredArgsConstructor
public class AdminSphereBiz extends BaseBiz {

    @NotNull
    private final SphereDao dao;
    @NotNull
    private final CategoryDao categoryDao;

    @NotNull
    private final IFeignLecturer feignLecturer;
    @NotNull
    private final IFeignRoleUser feignRoleUser;    

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;    
    
    /**
     * 全景信息分页
     *
     * @param req 全景信息分页查询参数
     * @return 全景信息分页查询结果
     */
    public Result<Page<AdminSpherePageResp>> page(AdminSpherePageReq req, Long userId) {
        SphereExample example = new SphereExample();
        Criteria c = example.createCriteria();
        if (StringUtils.hasText(req.getMingcheng())) {
            c.andMingchengLike(PageUtil.rightLike(req.getMingcheng()));
        }
        // 仅仅只有资源管理员角色，只能看到自己的资源
        if (feignRoleUser.isOnlyResourceManager(userId)) {
        	c.andUserIdEqualTo(userId);
        }        
        example.setOrderByClause("sphere_sort asc, id desc");
        Page<Sphere> page = dao.page(req.getPageCurrent(), req.getPageSize(), example);
        Page<AdminSpherePageResp> respPage = PageUtil.transform(page, AdminSpherePageResp.class);
//        if (CollUtil.isNotEmpty(respPage.getList())) {
//            List<Long> lecturerIdList = respPage.getList().stream().map(AdminSpherePageResp::getLecturerId).collect(Collectors.toList());
//            Map<Long, String> lecturerNameMap = feignLecturer.listByIds(lecturerIdList);
//
//            List<Long> categoryIdList = respPage.getList().stream().map(AdminSpherePageResp::getCategoryId).collect(Collectors.toList());
//            Map<Long, String> categoryNameMap = categoryDao.listByIds(categoryIdList).stream().collect(Collectors.toMap(Category::getId, Category::getCategoryName));
//
//            for (AdminSpherePageResp resp : respPage.getList()) {
//                resp.setLecturerName(lecturerNameMap.get(resp.getLecturerId()));
//                resp.setCategoryName(categoryNameMap.get(resp.getCategoryId()));
//            }
//        }
        return Result.success(respPage);
    }

    /**
     * 全景信息添加
     *
     * @param req 全景信息
     * @return 添加结果
     */
    public Result<String> save(AdminSphereSaveReq req, Long userId) {
        Sphere record = BeanUtil.copyProperties(req, Sphere.class);
        record.setUserId(userId);
        if (dao.save(record) > 0) {
            EsSphere esSphere = BeanUtil.copyProperties(record, EsSphere.class);
            elasticsearchRestTemplate.index(new IndexQueryBuilder().withObject(esSphere).build(), IndexCoordinates.of(EsSphere.SPHERE));        	
            return Result.success("操作成功");
        }
        return Result.error("操作失败");
    }

    /**
     * 全景信息查看
     *
     * @param id 主键ID
     * @return 全景信息
     */
    public Result<AdminSphereViewResp> view(Long id) {
        return Result.success(BeanUtil.copyProperties(dao.getById(id), AdminSphereViewResp.class));
    }

    /**
     * 全景信息修改
     *
     * @param req 全景信息修改对象
     * @return 修改结果
     */
    public Result<String> edit(AdminSphereEditReq req) {
        Sphere record = BeanUtil.copyProperties(req, Sphere.class);
        if (dao.updateById(record) > 0) {
            EsSphere esSphere = BeanUtil.copyProperties(record, EsSphere.class);
            elasticsearchRestTemplate.index(new IndexQueryBuilder().withObject(esSphere).build(), IndexCoordinates.of(EsSphere.SPHERE));
            return Result.success("操作成功");
        }
        return Result.error("操作失败");
    }

    /**
     * 全景信息删除
     *
     * @param id ID主键
     * @return 删除结果
     */
    public Result<String> delete(Long id) {
        if (dao.deleteById(id) > 0) {
        	elasticsearchRestTemplate.delete(id.toString(), EsSphere.class);
            return Result.success("操作成功");
        }
        return Result.error("操作失败");
    }
    
    public void syncEs() {
        // 获取全部全景
        SphereExample example = new SphereExample();
        example.createCriteria().andStatusIdEqualTo(StatusIdEnum.YES.getCode());
        List<Sphere> sphereList = dao.listByExample(example);
        if (CollUtil.isNotEmpty(sphereList)) {
            List<IndexQuery> queries = new ArrayList<>();
            for (Sphere sphere : sphereList) {
                EsSphere esSphere = BeanUtil.copyProperties(sphere, EsSphere.class);
                esSphere.setGmtCreate(DateUtil.fromLocalDateTime(sphere.getGmtCreate()));
                esSphere.setGmtModified(DateUtil.fromLocalDateTime(sphere.getGmtModified()));

                queries.add(new IndexQueryBuilder().withObject(esSphere).build());
            }
            // 更新es
            elasticsearchRestTemplate.indexOps(EsSphere.class).delete();
            elasticsearchRestTemplate.bulkIndex(queries, IndexCoordinates.of(EsSphere.SPHERE));
        }      
    }    
}
